package com.zhiche.lisa.bms.service.utils.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 导入工具类
 *
 * @param <T> 转换实体
 * @author liuanshun
 */
public class ImportUtil<T> extends ExcelCommon {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImportUtil.class);

    private boolean mapperKeyAreTitle = true;
    /**
     * 解析后的对象集合
     */
    private List<T> dataEntity;

    public ImportUtil() {
        this.dataEntity = Lists.newArrayList();
    }

    /**
     * 选定excel标识title的映射区域
     *
     * @param mapperKeyAreTitle 默认以true(key为标识title执行)，false则为value为标识
     * @return
     */
    public ImportUtil<T> setMapperKeyAreTitle(boolean mapperKeyAreTitle) {
        this.mapperKeyAreTitle = mapperKeyAreTitle;
        return this;
    }

    /**
     * 获取处理结果对象
     *
     * @return
     */
    public List<T> getDataEntity() {
        return dataEntity;
    }

    public Map<String, String> importToData(Class<T> classType, String dataExcelString, Map<String, Object> mappering) {

        String result = null;
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        JSONObject jsonObject = JSONObject.parseObject(dataExcelString);
        JSONArray arrayHeader = JSONObject.parseArray(jsonObject.getString("header"));
        if (arrayHeader != null) {
            arrayHeader.add("导入结果");
            arrayHeader.add("执行信息");
        }

        JSONArray arrayRows = JSONObject.parseArray(jsonObject.getString("rows"));
        List<String> keyList = getMapKey(mappering);
        List<String> valList = getMapVal(mappering);
        List<JSONObject> saveList = new ArrayList<>();
        for (int i = 0; i < arrayRows.size(); i++) {
            try {
                JSONObject entityJsonObj = arrayRows.getJSONObject(i);
                if (mapperKeyAreTitle) {
                    //若key值为title
                    for (int keyId = 0; keyList.size() > keyId; keyId++) {
                        String key = keyList.get(keyId);
                        if (entityJsonObj.containsKey(key)) {
                            entityJsonObj.put(valList.get(keyId), entityJsonObj.remove(key));
                        }
                    }
                } else {
                    //value值为title
                    for (int keyId = 0; valList.size() > keyId; keyId++) {
                        String key = valList.get(keyId);
                        if (entityJsonObj.containsKey(key)) {
                            Object keyValue = entityJsonObj.get(key);
                            if (Objects.nonNull(keyValue) && StringUtils.isNotBlank(keyValue.toString())) {
                                entityJsonObj.put(keyList.get(keyId), entityJsonObj.remove(key));
                            } else {
                                entityJsonObj.remove(key);
                            }
                        }
                    }
                }
                dataEntity.add(JSONObject.parseObject(JSONObject.toJSONString(entityJsonObj), classType));
                arrayRows.getJSONObject(i).put("导入结果", "成功");
                arrayRows.getJSONObject(i).put("执行信息", "成功");
            } catch (Exception e) {
                LOGGER.error("ImportUtil.importToData ERROR Message : {} ", e);
                arrayRows.getJSONObject(i).put("导入结果", "失败");
                arrayRows.getJSONObject(i).put("执行信息", e.getMessage());
            }
            JSONObject saveObject = (JSONObject) arrayRows.get(i);
            saveList.add(saveObject);
        }
        result = JSONArray.toJSONString(saveList);
        Map<String, String> map = new HashMap<>();
        map.put("header", JSONArray.toJSONString(arrayHeader));
        map.put("rows", result);
        return map;
    }
}
